package com.wetao.lib_common.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.StringUtil;
import com.wetao.lib_common.utils.ToastUtil;

import java.util.Timer;
import java.util.TimerTask;


public class PlayService  extends Service {
    private CallbackPlay callbackPlay;
    public static final int STATUS_MUSIC_IDE_PRE = 1000;//播放初始化之前
    public static final int STATUS_MUSIC_IDE = 1001;//播放初始化
    public static final int STATUS_MUSIC_PLAY = 1002;//播放
    public static final int STATUS_MUSIC_PAUSE = 1003;//暂停
    public static final int STATUS_MUSIC_STOP = 1004;//停止
    public static final int STATUS_MUSIC_COMPLETE = 1005;//播放完成
    public static final String STR_DURATION = "duration";
    public static final String STR_CURRENT_POSITION = "currentPosition";

    public static final String PX30_EINK = "px30_eink";

    private int mPlay_status = STATUS_MUSIC_IDE_PRE;
    private String mUrl;
    private MediaPlayer mediaPlayer;
    private AudioManager mAudioManager = null;
    private Timer timer;
    private TimerTask task;
    public static long testTime_2 = 0;

    @Override
    public IBinder onBind(Intent intent) {
        LogUtils.i("---onBind");
        // TODO: Return the communication channel to the service.
        //throw new UnsupportedOperationException("Not yet implemented");

        initMediaPlayer();
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        return new PlayBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.i("---onCreate");
    }

    @Override
    public void onDestroy() {
        LogUtils.i("---onDestroy");
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        LogUtils.i("---onUnbind");
        uninMediaPlayer();
        if (mAudioManager != null) {
            mAudioManager.abandonAudioFocus(mAudioFocusListener);
        }
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        LogUtils.i("---onRebind");
        super.onRebind(intent);
    }

    void initMediaPlayer() {
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
            if (mediaPlayer != null) {
                //mediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);
                MediaPlayerEvtListener listener = new MediaPlayerEvtListener();
                mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mediaPlayer) {
                        mPlay_status = STATUS_MUSIC_IDE;
                        refreshPosition(false);
                        //
                        if(callbackPlay != null) {
                            callbackPlay.onLoadedUrl();
                        }
                    }
                });
                mediaPlayer.setOnCompletionListener(listener);
                mediaPlayer.setOnErrorListener(listener);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            }
        } else {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.reset();
            if(timer != null) {
                timer.cancel();
            }
            if(callbackPlay != null) {
                mPlay_status = STATUS_MUSIC_STOP;
                callbackPlay.onMusicStausChange(mPlay_status);
            }
        }
    }

    void uninMediaPlayer() {
        if (mediaPlayer != null) {
            try {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    //ThreadPoolUtil.getScheduledExecutor().shutdown();
                }
                mediaPlayer.release();
                if(timer != null) {
                    timer.cancel();
                }
                if(task != null) {
                    task.cancel();
                }
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
            mediaPlayer = null;
        }
    }

    public String getmUrl() {
        return mUrl;
    }
    public void setmUrl(String url) {
        mUrl = url;
        mPlay_status = STATUS_MUSIC_IDE_PRE;
        initMediaPlayer();
        if(StringUtil.isEmpty(mUrl)) {
            if(callbackPlay != null) {
                callbackPlay.onCurrentPosition(0, 0);
            }
            return; //2020-03-09
        }
        if(mediaPlayer == null) {
            return;
        }
        try {
            mediaPlayer.setDataSource(url);
            mediaPlayer.prepareAsync();// 进行缓冲
            //mediaPlayer.seekTo(0);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    // 播放音乐的方法
    public void playMusic() {
        if(mUrl == null || "".equals(mUrl.trim())) {
            ToastUtil.initToast("没有语音批注");
            return;
        }
        if(mPlay_status == STATUS_MUSIC_IDE_PRE
                || mPlay_status == STATUS_MUSIC_PLAY
        ) {
            return;
        }
        int status = mAudioManager.requestAudioFocus(mAudioFocusListener,
                AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);
        if (status == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
            return;
        }
        try {
            LogUtils.i("没有正在播放，开始操作");
            mediaPlayer.start();
            mPlay_status = STATUS_MUSIC_PLAY;
            // 更新进度条
            updateSeekBar();
            if(callbackPlay != null) {
                callbackPlay.onMusicStausChange(mPlay_status);
            }
            LogUtils.i("音乐播放了");
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    // 暂停音乐的方法
    public void pauseMusic() {
        if (mPlay_status == STATUS_MUSIC_PLAY) {
            // 暂停音乐
            mediaPlayer.pause();
            mPlay_status = STATUS_MUSIC_PAUSE;
            timer.cancel();
            if(callbackPlay != null) {
                callbackPlay.onMusicStausChange(mPlay_status);
            }
            LogUtils.i("音乐暂停了");
        }
    }

    public void resumeMusic() {
        if (mPlay_status == STATUS_MUSIC_PAUSE) {
            mediaPlayer.start();
            mPlay_status = STATUS_MUSIC_PLAY;
            updateSeekBar();
            if(callbackPlay != null) {
                callbackPlay.onMusicStausChange(mPlay_status);
            }
            LogUtils.i("音乐暂停了");
        }
    }

    public void stopMusic() {
        if (mPlay_status == STATUS_MUSIC_PLAY
                || mPlay_status == STATUS_MUSIC_PAUSE) {
            mediaPlayer.stop();
            mPlay_status = STATUS_MUSIC_STOP;
            // 如果不取消定时任务，mediaplayer停止就崩了
            timer.cancel();
            //task.cancel();
            //mediaPlayer = null;
            if(callbackPlay != null) {
                callbackPlay.onMusicStausChange(mPlay_status);
            }
        }
    }

    private boolean playSpeed(float speed) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                PlaybackParams params = mediaPlayer.getPlaybackParams();
                params.setSpeed(speed);
                mediaPlayer.setPlaybackParams(params);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    // 实现指定播放的位置
    public void seekTo(int position) {
        if (mediaPlayer == null) {
            return ;
        }
        mediaPlayer.seekTo(position);
        //只有在播放状态才会拖动后重新播放
        if(isPlaying()) {
            //playMusic();
            //pauseMusic();
        }
    }

    public long position() {
        if (mediaPlayer == null) {
            return 0;
        }
        //Logger.i(mPlayer.getCurrentPosition() + "");
        //Logger.i(mPlayer.getDuration() + "");
        return mediaPlayer.getCurrentPosition();
    }

    public long duration() {
        if (mediaPlayer == null) {
            return 0;
        }
        return mediaPlayer.getDuration();
    }

    public boolean isPlaying() {
        if (mediaPlayer == null) {
            return false;
        }
        return mediaPlayer.isPlaying();
    }

    private AudioManager.OnAudioFocusChangeListener mAudioFocusListener = new AudioManager.OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {
        }
    };

    private class MediaPlayerEvtListener implements
            MediaPlayer.OnCompletionListener,
            MediaPlayer.OnErrorListener {

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            switch (what) {
                case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
                case MediaPlayer.MEDIA_ERROR_TIMED_OUT: {
                } break;
                case MediaPlayer.MEDIA_ERROR_UNKNOWN:
                case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                case MediaPlayer.MEDIA_ERROR_IO:
                case MediaPlayer.MEDIA_ERROR_MALFORMED:
                case MediaPlayer.MEDIA_ERROR_UNSUPPORTED: {
                    uninMediaPlayer();
                    initMediaPlayer();
                    return true;
                }
                default:
                    break;
            }
            return false;
        }

        @Override
        public void onCompletion(MediaPlayer mp) {
            LogUtils.i("歌曲播放完成");
            if (timer!=null){
                timer.cancel();
            }
            //task.cancel();
            //seekTo(0);
            refreshPosition(true);
            mPlay_status = STATUS_MUSIC_COMPLETE;
            if(callbackPlay != null) {
                callbackPlay.onMusicStausChange(mPlay_status);
                callbackPlay.onCompletion();
            }
        }
    }

    private void updateSeekBar() {
        // 使用Timer 定时器去获取当前进度
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                refreshPosition(false);
            }
        };
        // 100ms后每间隔1s、执行一次run方法
        //timer.schedule(task, 100, 1000);
        timer.schedule(task, 100, 200);

    }

    private void refreshPosition(boolean isCompletion) {
        if(mediaPlayer == null || mPlay_status == STATUS_MUSIC_IDE_PRE) {
            return;
        }
        // 一秒钟获取一次当前进度
        int currentPosition = 0;
        int duration = 0;
        if(!isCompletion && mediaPlayer.isPlaying()) {
            currentPosition = mediaPlayer.getCurrentPosition();
            // 获取当前歌曲总长度
        }
        duration = mediaPlayer.getDuration();

        if(callbackPlay != null) {
            callbackPlay.onCurrentPosition(currentPosition, duration);
        }
    }

    public class PlayBinder extends Binder {
        public String getServiceTestData() {
            return "测试服务数据";
        }
        public PlayService getService() {
            return PlayService.this;
        }

        public void callSetmUrl(String url) {
            setmUrl(url);
        }

        public boolean callIsPlaying() {
            return isPlaying();
        }

        public int callPlayStatus() {
            return mPlay_status;
        }

        public void callSetPlayStatus(int status) {
            mPlay_status = status;
        }

        public void callPlayMusic() {
            playMusic();
        }

        public void callPauseMusic() {
            pauseMusic();
        }

        public void callResumeMusic() {
            resumeMusic();
        }

        public void callStopMusic() {
            stopMusic();
        }

        public void callPlaySpeed(float speed) {
            playSpeed(speed);
        }

        public void callSeekTo(int position) {
            seekTo(position);
        }
    }

    public void setCallback(CallbackPlay callback) {
        this.callbackPlay = callback;
    }

    public CallbackPlay getCallback() {
        return callbackPlay;
    }

    public interface CallbackPlay {
        void onDataTestChange(String data);
        void onMusicStausChange(int status);
        void onCurrentPosition(int currentPosition, int duration);
        void onCompletion();
        void OnDuration(int duration);
        void onLoadedUrl();
    }
}
